package com.washmadam.service.domain.order;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.github.pagehelper.PageInfo;
import com.washmadam.service.common.enums.DeleteEnum;
import com.washmadam.service.common.enums.PeriodTypeEnum;
import com.washmadam.service.common.enums.RenewalStatusEnum;
import com.washmadam.service.common.enums.ReserveEnableEnum;
import com.washmadam.service.common.enums.ReserveStatusEnum;
import com.washmadam.service.common.enums.ServiceStatusEnum;
import com.washmadam.service.common.enums.StatusEnum;
import com.washmadam.service.common.utils.DateUtils;
import com.washmadam.service.db.dto.Customer;
import com.washmadam.service.db.dto.CustomerOrder;
import com.washmadam.service.db.dto.CustomerOrderCommunicate;
import com.washmadam.service.db.dto.CustomerOrderService;
import com.washmadam.service.db.request.operate.CustomerOrderOperateParam;
import com.washmadam.service.db.request.query.CustomerOrderQueryParam;
import com.washmadam.service.db.response.CustomerOrderResponse;
import com.washmadam.service.service.communicate.CustomerOrderCommunicateQueryService;
import com.washmadam.service.service.customer.CustomerOperateService;
import com.washmadam.service.service.order.CustomerOrderOperateService;
import com.washmadam.service.service.order.CustomerOrderQueryService;
import com.washmadam.service.service.service.CustomerOrderServiceOperateService;
import com.washmadam.service.service.service.CustomerOrderServiceQueryService;

@Component
public class CustomerOrderDomain {
	@Autowired
	CustomerOperateService customerOperateService;
	@Autowired
	CustomerOrderOperateService customerOrderOperateService;
	@Autowired 
	CustomerOrderQueryService customerOrderQueryService;
	@Autowired
	CustomerOrderServiceOperateService customerOrderServiceOperateService;
	@Autowired
	CustomerOrderServiceQueryService customerOrderServiceQueryService;
	@Autowired
	CustomerOrderCommunicateQueryService customerOrderCommunicateQueryService;
	
	public void saveCustomerOrder(CustomerOrderOperateParam requestParam) {
		//新增订单-若会员不存在则新增会员
		Customer customer = customerOperateService.saveAndGetCustomer(requestParam);
		requestParam.setCustomerId(customer.getId());
		if(requestParam.getTotalNum()==null) {
			requestParam.setTotalNum(requestParam.getCurrentNum());
		}
		if(StringUtils.isBlank(requestParam.getOriginBottleNum())) {
			requestParam.setOriginBottleNum(requestParam.getBottleNum());
		}
		if(requestParam.getHandleDate() == null) {
			requestParam.setHandleDate(new Date());
		}
		if(CollectionUtils.isNotEmpty(requestParam.getCustomerAddressList())) {
			requestParam.setAllCustomerAddress(StringUtils.join(requestParam.getCustomerAddressList(),","));
		}else {
			requestParam.setAllCustomerAddress(requestParam.getCustomerAddress());
		}
		Date nextServiceDate = requestParam.getNextServiceDate();
		if(nextServiceDate == null) {
			if(requestParam.getPeriodType()==null ||requestParam.getPeriodType()==PeriodTypeEnum.DAY.getType()) {
				requestParam.setPeriodType(PeriodTypeEnum.DAY.getType());
				nextServiceDate = DateUtils.addDays(DateUtils.getCurrentDate(), requestParam.getServicePeriod());
			}else {
				requestParam.setPeriodType(PeriodTypeEnum.MONTH.getType());
				nextServiceDate = DateUtils.addMonths(DateUtils.getCurrentDate(), requestParam.getServicePeriod());
			}
		}
		Date endServiceDate;
		if(requestParam.getPeriodType()==null ||requestParam.getPeriodType()==PeriodTypeEnum.DAY.getType()) {
			requestParam.setPeriodType(PeriodTypeEnum.DAY.getType());
			endServiceDate = DateUtils.addDays(DateUtils.getBeginDate(nextServiceDate), (requestParam.getServicePeriod()*(requestParam.getCurrentNum()-1)));
		}else {
			requestParam.setPeriodType(PeriodTypeEnum.MONTH.getType());
			endServiceDate = DateUtils.addMonths(DateUtils.getBeginDate(nextServiceDate), (requestParam.getServicePeriod()*(requestParam.getCurrentNum()-1)));
		}
		requestParam.setNextServiceDate(nextServiceDate);
		requestParam.setFirstServiceDate(DateUtils.getCurrentDate());
		requestParam.setEndServiceDate(endServiceDate);
		requestParam.setReserveStatus(ReserveStatusEnum.UN_RESERVE.getCode());
		requestParam.setRenewalStatus(RenewalStatusEnum.INIT.getCode());
		requestParam.setReserveEnable(ReserveEnableEnum.OPEN.getCode());
		customerOrderOperateService.saveOrUpdateOrder(requestParam);
		//初始化一份服务数据
		CustomerOrderService customerOrderService = new CustomerOrderService();//customerOrderServiceQueryService.getCurrentCustomerOrderServiceByOrderId(customerOrder.getId(),customerOrder.getCurrentNum()-1);
		customerOrderService.setCustomerId(requestParam.getCustomerId());
		customerOrderService.setCustomerName(requestParam.getCustomerName());
		customerOrderService.setContactMobile(requestParam.getContactMobile());
		customerOrderService.setOtherContactMobile(requestParam.getOtherContactMobile());
		customerOrderService.setCustomerAddress(requestParam.getCustomerAddress());
		customerOrderService.setServiceNum(1);
		customerOrderService.setServiceStatus(ServiceStatusEnum.NORMAL.getCode());
		customerOrderService.setCustomerOrderId(requestParam.getId());
		customerOrderService.setStatus(StatusEnum.ENABLE.getCode());
		customerOrderService.setCreateBy(requestParam.getCreateBy());
		customerOrderService.setCreateTime(new Date());
		customerOrderService.setUpdateBy(requestParam.getCreateBy());
		customerOrderService.setUpdateTime(new Date());
		customerOrderServiceOperateService.saveOrUpdateCustomerOrderService(customerOrderService);
	}
	
	public void saveRenewalCustomerOrder(CustomerOrderOperateParam requestParam) {
		//查询是否有过期订单，如果存在过期订单，则作废之前订单
		customerOrderOperateService.renewalOldCustomerOrderById(requestParam);
		saveCustomerOrder(requestParam);
	}

	public void editCustomerOrder(CustomerOrderOperateParam requestParam) {
		CustomerOrder customerOrder = customerOrderQueryService.getCustomerOrderById(requestParam.getId());
		if(customerOrder==null) {
			throw new RuntimeException("订单查询失败");
		}
		//服务次数变动
		int serviceNumDiff = 0;
		if(requestParam.getCurrentNum() !=customerOrder.getCurrentNum()) {
			serviceNumDiff = requestParam.getCurrentNum()-customerOrder.getCurrentNum();
		}
		if(requestParam.getHandleDate() == null) {
			requestParam.setHandleDate(new Date());
		}
		if(CollectionUtils.isNotEmpty(requestParam.getCustomerAddressList())) {
			requestParam.setAllCustomerAddress(StringUtils.join(requestParam.getCustomerAddressList(),","));
		}else {
			requestParam.setAllCustomerAddress(requestParam.getCustomerAddress());
		}
		requestParam.setTotalNum(customerOrder.getTotalNum()+serviceNumDiff);
		Date nextServiceDate = requestParam.getNextServiceDate();
		if(nextServiceDate == null) {
			if(requestParam.getPeriodType()==null ||requestParam.getPeriodType()==PeriodTypeEnum.DAY.getType()) {
				requestParam.setPeriodType(PeriodTypeEnum.DAY.getType());
				nextServiceDate = DateUtils.addDays(DateUtils.getCurrentDate(), requestParam.getServicePeriod());
			}else {
				requestParam.setPeriodType(PeriodTypeEnum.MONTH.getType());
				nextServiceDate = DateUtils.addMonths(DateUtils.getCurrentDate(), requestParam.getServicePeriod());
			}
		}
		Date endServiceDate;
		if(requestParam.getPeriodType()==null ||requestParam.getPeriodType()==PeriodTypeEnum.DAY.getType()) {
			requestParam.setPeriodType(PeriodTypeEnum.DAY.getType());
			endServiceDate = DateUtils.addDays(DateUtils.getBeginDate(nextServiceDate), (requestParam.getServicePeriod()*(requestParam.getCurrentNum()-1)));
		}else {
			requestParam.setPeriodType(PeriodTypeEnum.MONTH.getType());
			endServiceDate = DateUtils.addMonths(DateUtils.getBeginDate(nextServiceDate), (requestParam.getServicePeriod()*(requestParam.getCurrentNum()-1)));
		}
		requestParam.setNextServiceDate(nextServiceDate);
		requestParam.setEndServiceDate(endServiceDate);
		customerOrderOperateService.saveOrUpdateOrder(requestParam);
	}

	public void deleteOrder(CustomerOrderOperateParam requestParam) {
		CustomerOrder customerOrder = customerOrderQueryService.getCustomerOrderById(requestParam.getId());
		if(customerOrder==null) {
			throw new RuntimeException("订单查询失败");
		}
		requestParam.setIsDelete(DeleteEnum.DELETE.getCode());
		customerOrderOperateService.saveOrUpdateOrder(requestParam);
	}

	public void refundOrder(CustomerOrderOperateParam requestParam) {
		CustomerOrder customerOrder = customerOrderQueryService.getCustomerOrderById(requestParam.getId());
		if(customerOrder==null) {
			throw new RuntimeException("订单查询失败");
		}
		requestParam.setStatus(StatusEnum.PROHIBIT.getCode());
		customerOrderOperateService.saveOrUpdateOrder(requestParam);
	}

	public CustomerOrder getCustomerOrderInfo(Long id) {
		CustomerOrder customerOrder = customerOrderQueryService.getCustomerOrderById(id);
		if(customerOrder==null) {
			throw new RuntimeException("订单查询失败");
		}
		
		CustomerOrderResponse response = coverResponse(customerOrder);
		List<CustomerOrderService> customerOrderServiceList = customerOrderServiceQueryService.getAllCompletedCustomerOrderServiceByOrderId(customerOrder.getId());
		response.setServiceList(customerOrderServiceList);
		if(response.getServiceList()==null) {
			response.setServiceList(new ArrayList<CustomerOrderService>());
		}
		List<CustomerOrderCommunicate> customerOrderCommunicateList = customerOrderCommunicateQueryService.getAllCustomerOrderCommunicateByOrderId(customerOrder.getId());
		response.setCommunicateList(customerOrderCommunicateList);
		if(response.getCommunicateList()==null) {
			response.setCommunicateList(new ArrayList<CustomerOrderCommunicate>());
		}
		return response;
	}

	public PageInfo<CustomerOrder> getCustomerOrderList(CustomerOrderQueryParam requestParam) {
		PageInfo<CustomerOrder> result = customerOrderQueryService.getCustomerOrderList(requestParam);
		List<CustomerOrder> list = result.getList();
		if(CollectionUtils.isNotEmpty(list)) {
			List<CustomerOrder> queryList = list.stream().map((CustomerOrder data)->coverResponse(data)).collect(Collectors.toList());
			result.setList(queryList);
		}
		return result;
	}

	private CustomerOrderResponse coverResponse(CustomerOrder data) {
		CustomerOrderResponse response = new CustomerOrderResponse();
		BeanUtils.copyProperties(data, response);
		if(StringUtils.isNotBlank(response.getAllCustomerAddress())) {
			response.setCustomerAddressList(Arrays.asList(response.getAllCustomerAddress().split(",")));
		}
		try {
			response.setCompletedServiceNum(data.getTotalNum()-data.getCurrentNum());
			int dateDiff = DateUtils.daysBetween(new Date(),data.getNextServiceDate());
			response.setRemainingDays(dateDiff);
			if(data.getReserveStatus() == ReserveStatusEnum.RESERVE_ERROR.getCode()) {
				CustomerOrderCommunicate customerOrderCommunicate = customerOrderCommunicateQueryService.getLastCommunicateMessage(data.getId());
				if(customerOrderCommunicate!=null) {
					response.setCommunicateDetail(customerOrderCommunicate.getCommunicateResult());
				}
			}
			if(data.getReserveStatus() == ReserveStatusEnum.MEMBER_END.getCode()) {
				CustomerOrderCommunicate customerOrderCommunicate = customerOrderCommunicateQueryService.getLastCommunicateMessage(data.getId());
				if(customerOrderCommunicate!=null && customerOrderCommunicate.getCustomerOrderSerivceId()==null) {
					response.setCommunicateDetail(customerOrderCommunicate.getCommunicateResult());
				}
			}
			if(data.getReserveStatus() == ReserveStatusEnum.RESERVE.getCode()) {
				CustomerOrderService customerOrderService = customerOrderServiceQueryService.getLastOrderServiceByOrderId(data.getId());
				if(customerOrderService!=null) {
					response.setReservePerson(customerOrderService.getAppointmentPerson());
					response.setReserveDate(customerOrderService.getAppointmentDate());
					response.setReserveContactPerson(customerOrderService.getCustomerName());
					response.setReserveContactMobile(customerOrderService.getContactMobile());
					response.setReserveAddress(customerOrderService.getCustomerAddress());
				}
			}
		}catch(Exception e) {
		}
		return response;
	}

	public void notRemindOrder(CustomerOrderOperateParam requestParam) {
		CustomerOrder customerOrder = customerOrderQueryService.getCustomerOrderById(requestParam.getId());
		if(customerOrder==null) {
			throw new RuntimeException("订单查询失败");
		}
		requestParam.setReserveEnable(ReserveEnableEnum.CLOSE.getCode());
		customerOrderOperateService.saveOrUpdateOrder(requestParam);
	}

	public void remindOrder(CustomerOrderOperateParam requestParam) {
		CustomerOrder customerOrder = customerOrderQueryService.getCustomerOrderById(requestParam.getId());
		if(customerOrder==null) {
			throw new RuntimeException("订单查询失败");
		}
		requestParam.setReserveEnable(ReserveEnableEnum.OPEN.getCode());
		customerOrderOperateService.saveOrUpdateOrder(requestParam);
	}


}
